<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>loadImage</title>
    <style>
        body {
            margin: 0;
            padding: 15px;
        }

        .img-box {
            box-sizing: border-box;
            width: 400px;
            height: 300px;
            border-radius: 8px;
            box-shadow: 2px 1px 8px rgba(0, 0, 0, .3);
            color: rgba(0, 0, 0, .85);
            background-repeat: no-repeat;
            background-size: cover;
            background-position: center;
            text-align: center;
            line-height: 300px;
        }

        .load-img-btn {
            border: 1px solid #232323;
            color: rgba(0, 0, 0, .85);
            padding: 12px 24px;
            transition: all .3s;
            background-color: transparent;
            display: inline-block;
            margin-top: 15px;
            cursor: pointer;
            border-radius: 5px;
        }

        .load-img-btn:hover {
            border-color: #2396ef;
            color: #2396ef;
        }
    </style>
</head>

<body>
    <div id="imageBox" class="img-box"></div>
    <button type="button" id="loadImageBtn" class="load-img-btn">点击加载图像</button>
    <script>
        const api = 'https://api.thecatapi.com/v1/images/search?size=full';
        const box = document.querySelector('#imageBox');
        const btn = document.querySelector('#loadImageBtn');
        const loadImage = src => new Promise((resolve, reject) => {
            const img = new Image();
            img.src = src;
            img.onload = () => resolve(img.src);
            img.onerror = () => reject();
        });
        btn.addEventListener('click', () => {
            fetch(api).then(res => res.json()).then(async v => {
                const [{ url }] = v;
                box.textContent = '图像正在加载中.....';
                const src = await loadImage(url);
                box.style.backgroundImage = `url(${src})`;
                box.textContent = '';
            })
        })
    </script>
</body>

</html>